package com.bw.gmall.realtime.app.dim;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bw.gmall.realtime.app.func.TableProcessFunction;
import com.bw.gmall.realtime.bean.TableProcess;
import com.bw.gmall.realtime.utils.MyKafkaUtil;
import com.bw.gmall.realtime.utils.MyPhoenixSink;
import com.bw.gmall.realtime.utils.MysqlUtil;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.streaming.api.datastream.*;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class DimApp {
    public static void main(String[] args) throws Exception {
        //获取流式环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //设置并行度
        env.setParallelism(1);

        //读取kafka数据
        DataStreamSource<String> ds = env.addSource(MyKafkaUtil.getFlinkKafkaConsumer("topic_db", "dim_app"));
//        ds.print();
        //过滤非json格式数据  保留初始数据  新增及变化数据
        SingleOutputStreamOperator<JSONObject> filterDs = ds.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                try {
                    JSONObject jsonObject = JSON.parseObject(value);
                    String type = jsonObject.getString("type");
                    if ("insert".equals(jsonObject.getString("type")) || "update".equals(jsonObject.getString("type"))) {
                        out.collect(jsonObject);
                    }
                } catch (Exception e) {
                    System.out.println("数据格式异常" + value);
                }
            }
        });
        filterDs.print("过滤后数据");
        // 使用FlinkCDC  读取mysql 配置信息表    创建配置流

        DataStream<String> mysqlDs = MysqlUtil.cdcMysql(env, "gmall_config", "table_process");
        //将配置流处理为广播流
        MapStateDescriptor<String, TableProcess> mapState = new MapStateDescriptor<>("mapState", String.class, TableProcess.class);
        BroadcastStream<String> broadcast = mysqlDs.broadcast(mapState);

        //主流与广播流进行连接
        BroadcastConnectedStream<JSONObject, String> connect = filterDs.connect(broadcast);
        //处理连接流   根据配置信息处理主流数据（将配置信息存入到状态中  主流读状态）
        SingleOutputStreamOperator<JSONObject> dimDs = connect.process(new TableProcessFunction(mapState));

        //将数据写入到Phoenix
        dimDs.addSink(new MyPhoenixSink());

        //启动
        env.execute();
    }
}
